package com.itheima.reggie.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.Data;

import java.util.Calendar;
import java.util.Map;

@Data
public class JWTUtil {

    //签名在加密和解密的时候都会用到，所以定义成静态常量
    private static final String SIGN = "!@#$%Q&T#R131242343^YTR";

    /*
     * 生成token   header.payload.sing
     * */
    public static String getToken(Map<String,String> map) {
        //反射创建时间对象
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, 7);  //默认七天过期

        //遍历前端传入的map集合
        JWTCreator.Builder builder = JWT.create();
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });

        String token = builder.withExpiresAt(instance.getTime())  //指定令牌过期时间
                .sign(Algorithm.HMAC256(SIGN));//签名

        /*String token = JWT.create()
                .withClaim("userId", 12)
                .withClaim("username", "admin")   //payload
                .withExpiresAt(instance.getTime())     //指定过期时间
                .sign(Algorithm.HMAC256(SIGN));   //签名*/
        return token;
    }


    /*验证token*/
   /* public static void verify(String token){
        JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
    }*/
    /*获取token信息*/
    public static DecodedJWT getTokenInfo(String token){
        return JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
    }
}
